/**
 * 
 */
package com.googlecode.c4e.mylyn.task.actions;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import com.googlecode.c4e.api.ProjectStates;
import com.googlecode.c4e.api.Registry;
import com.googlecode.c4e.api.model.BuildResult;
import com.googlecode.c4e.api.model.Project;

/**
 * @author gfernandes
 */
public class CreateMylynTaskAction implements IObjectActionDelegate {
	private Shell shell;
	private Project selected;

	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		this.shell = targetPart.getSite().getShell();
	}

	public void run(IAction action) {
		if(this.selected != null) {
			try {
				ProjectTaskMapping taskMapping = new ProjectTaskMapping();
				
				BuildResult build = Registry.getDefault().lastBuildResult(this.selected);
				taskMapping.setSummary("Continuum build #" + build.getBuildNumber() + " state: " + this.getProjectState() +  " project: " + this.selected.getName());
				taskMapping.setDescription(build.getOutput());
				
				TasksUiUtil.openNewTaskEditor(shell, taskMapping, null);
			} catch (Exception e) {
				TasksUiUtil.openNewTaskEditor(shell, null, null);
			}
		} else {
			TasksUiUtil.openNewTaskEditor(shell, null, null);
		}
	}

	private String getProjectState() {
		switch (this.selected.getState()) {
		case ProjectStates.FAILED:
			return "FAILED";
		case ProjectStates.ERROR:
			return "ERROR";
		default:
			return "unknown";
		}
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection != null && selection instanceof IStructuredSelection) {
			IStructuredSelection structuredSelection = (IStructuredSelection) selection;
			if (structuredSelection.getFirstElement() instanceof Project) {
				Project project = (Project) structuredSelection.getFirstElement();
				if(project.getState() == ProjectStates.FAILED || project.getState() == ProjectStates.ERROR) {
					this.selected = project;
				}
				else {
					this.selected = null;
					action.setEnabled(false);
				}
			}
		}
	}
}
